﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Administrator
{
    public partial class fSetting : Form
    {
        private ucDeviceCE cDeviceCE = null;
        private ucJoinChannel cJoinChannel = null;
        private ucJoinLineLosts cJoinLineLosts = null;
        private ucJoinReportGroup cJoinReportGroup = null;
        private ucMeter cMeter = null;
        private ucCommGroup cCommGroup = null;
        private ucUser cUser = null;
        private ucNewDeviceType cNewDeviceType = null;
        private ucPulseMetersCount cPulseMeterCount = null;

        private Byte[] tmpFreeEnergyTypes = new Byte[0];
        //Коммутационное оборудование устройств
        public String DeviceCECaption = "";
        public Int32 DeviceCEChannel = 0;
        
        //Группы отчетов присоединений
        public Int32 tmpReportGroupType = 0;
        public Byte tmpGroupID = 0;

        //Каналы учета присоединений
        public Int32 ChannelID = -1;
        public Boolean ChannelCollectEnable = false;
        public Byte ChannelEnergyType = 0;
        public String ChannelMeterSerial = "";
        public Int32 ChannelMeterID = -1;
        public String ChannelExportNPATSCode = "";
        public String ChannelImportNPATSCode = "";
        public String ChannelValue63002Code = "";
        public String ChannelASKPIdentifier = "";

        //Линии электропередач присоединений
        public Double CLLLineLength = 0;
        public Double CLLResistance = 0;
        public Double CLLUNominal = 0;
        public Double CLLCableLost = 0;
        public Double CLLAirLost = 0;
        public Int32 CLLCircuitsAmount = 0;

        public Int32 MeterIdx = -1;
        public Int32 UserIdx = -1;

        // параметры нового устройства
        Byte m_NewDevTypeIsUSPD = 0;
        int m_NewDevTypeMCCount = 0;

        int m_PulseMetersCount = 0;

        public fSetting()
        {
            InitializeComponent();
        }

        //Отображение формы настроек для коммутационного оборудования устройтсва
        public void FillDeviceCE(String Caption, Int32 Channel)
        {
            DeviceCECaption = Caption;
            DeviceCEChannel = Channel;

            cDeviceCE = new ucDeviceCE();
            cDeviceCE.Dock = DockStyle.Fill;
            cDeviceCE.Parent = pnlSetting;
            cDeviceCE.FillFields(DeviceCECaption, DeviceCEChannel);
            cDeviceCE.Show();
            cDeviceCE.BringToFront();
            cDeviceCE.Focus();
        }
        //Отображение формы настроек для канала учета присоединения
        public void FillJoinChannelSetting(cMain.CHANNEL Channel, Byte[] FreeEnergyTypes)
        {
            tmpFreeEnergyTypes = new Byte[FreeEnergyTypes.Length];
            for (Int32 i = 0; i < FreeEnergyTypes.Length; i++)
                tmpFreeEnergyTypes[i] = FreeEnergyTypes[i];
            ChannelID = Channel.ID;
            ChannelCollectEnable = Channel.CollectEnable;
            ChannelEnergyType = Channel.EnergyType;
            ChannelMeterSerial = Channel.MeterSerial;
            ChannelMeterID = Channel.MeterID;
            ChannelExportNPATSCode = Channel.ExportNPATSCode;
            ChannelImportNPATSCode = Channel.ImportNPATSCode;
            ChannelValue63002Code = Channel.Value63002Code;
            ChannelASKPIdentifier = Channel.ASKPIdentifier;
            
            cJoinChannel = new ucJoinChannel();
            cJoinChannel.Dock = DockStyle.Fill;
            cJoinChannel.Parent = pnlSetting;
            cJoinChannel.FillFields(ChannelID, ChannelCollectEnable, ChannelEnergyType, ChannelMeterSerial, ChannelMeterID, ChannelExportNPATSCode, ChannelImportNPATSCode, ChannelValue63002Code, ChannelASKPIdentifier);
            cJoinChannel.Show();
            cJoinChannel.BringToFront();
            cJoinChannel.Focus();
        }        
        //Отображение формы настроек потерь в линиях электропередач
        public void FillJoinConnLineLostsSetting(cMain.CONN_LINE_LOSTS ConnLineLosts)
        {
            CLLLineLength = ConnLineLosts.LineLength;
            CLLResistance = ConnLineLosts.Resistance;
            CLLUNominal = ConnLineLosts.UNominal;
            CLLCableLost = ConnLineLosts.CableLost;
            CLLAirLost = ConnLineLosts.AirLost;
            CLLCircuitsAmount = ConnLineLosts.CircuitsAmount;
            
            cJoinLineLosts = new ucJoinLineLosts();
            cJoinLineLosts.Dock = DockStyle.Fill;
            cJoinLineLosts.Parent = pnlSetting;
            cJoinLineLosts.FillSetting(CLLLineLength, CLLResistance, CLLUNominal, CLLCableLost, CLLAirLost, CLLCircuitsAmount);
            cJoinLineLosts.Show();
            cJoinLineLosts.BringToFront();
            cJoinLineLosts.Focus();
        }
        //Отображение формы настроек группы отчетов
        public void FillJoinReportGroupSetting(Int32 ReportGroupType)
        {
            if (ReportGroupType < cMain.ReportGroupList.Length)
            {
                tmpReportGroupType = ReportGroupType;

                cJoinReportGroup = new ucJoinReportGroup();
                cJoinReportGroup.Dock = DockStyle.Fill;
                cJoinReportGroup.Parent = pnlSetting;
                cJoinReportGroup.FillSetting(tmpReportGroupType);
                cJoinReportGroup.Show();
                cJoinReportGroup.BringToFront();
                cJoinReportGroup.Focus();
            }
        }
        //Отображение формы настроек счетчика из справочника
        public void FillMeterSetting(Int32 Idx)
        {
            cMain.METER_SETTING tmpMeter = new cMain.METER_SETTING();
            MeterIdx = Idx;
            tmpMeter.ItemAction.DBExist = cMain.MeterList[Idx].ItemAction.DBExist;
            tmpMeter.ItemAction.Changed = cMain.MeterList[Idx].ItemAction.Changed;
            tmpMeter.ItemAction.Deleted = cMain.MeterList[Idx].ItemAction.Deleted;
            tmpMeter.ID = cMain.MeterList[Idx].ID;
            tmpMeter.Caption = cMain.MeterList[Idx].Caption;
            tmpMeter.Precision = cMain.MeterList[Idx].Precision;
            tmpMeter.BeforeComma = cMain.MeterList[Idx].BeforeComma;
            tmpMeter.AfterComma = cMain.MeterList[Idx].AfterComma;
            tmpMeter.MeterConst = cMain.MeterList[Idx].MeterConst;
            tmpMeter.Phase = cMain.MeterList[Idx].Phase;
            tmpMeter.SelfDemand = cMain.MeterList[Idx].SelfDemand;

            cMeter = new ucMeter();
            cMeter.Dock = DockStyle.Fill;
            cMeter.Parent = pnlSetting;
            cMeter.FillSetting(tmpMeter);
            cMeter.Show();
            cMeter.BringToFront();
            cMeter.Focus();
        }
        //Отображение формы настроек группы канала связи
        public void FillCommChanGroupSetting(Byte GroupID)
        {
            tmpGroupID = GroupID;

            cCommGroup = new ucCommGroup();
            cCommGroup.Dock = DockStyle.Fill;
            cCommGroup.Parent = pnlSetting;
            cCommGroup.FillSetting(tmpGroupID);
            cCommGroup.Show();
            cCommGroup.BringToFront();
            cCommGroup.Focus();
        }
        //Отображение формы настроек пользователей
        public void FillUserSetting(Int32 Index)
        {
            UserIdx = Index;

            cUser = new ucUser();
            cUser.Dock = DockStyle.Fill;
            cUser.Parent = pnlSetting;
            cUser.FillFields(cMain.UserList[UserIdx].Caption, cMain.UserList[UserIdx].AccessID);
            cUser.Show();
            cUser.BringToFront();
            cUser.Focus();
        }

        public void FillAddNewDeviceInDictionary(Int32 Index)
        {
            UserIdx = Index;

            cNewDeviceType = new ucNewDeviceType();
            cNewDeviceType.Dock = DockStyle.Fill;
            cNewDeviceType.Parent = pnlSetting;
            //cNewDeviceType.FillFields(cMain.UserList[UserIdx].Caption, cMain.UserList[UserIdx].AccessID);
            cNewDeviceType.Show();
            cNewDeviceType.BringToFront();
            cNewDeviceType.Focus();
        }

        public void FillPulseMeterCount(Int32 Count)
        {
            //UserIdx = Index;
            cPulseMeterCount = new ucPulseMetersCount();

            cPulseMeterCount.Dock = DockStyle.Fill;
            cPulseMeterCount.Parent = pnlSetting;
            cPulseMeterCount.FillFields(Count);
            cPulseMeterCount.Show();
            cPulseMeterCount.BringToFront();
            cPulseMeterCount.Focus();
        }

        //Очистка рабочей области формы
        private void ClearWorkArea()
        {
            if (cDeviceCE != null) cDeviceCE.Dispose();            
            cDeviceCE = null;
            if (cJoinChannel != null) cJoinChannel.Dispose();
            cJoinChannel = null;
            if (cJoinLineLosts != null) cJoinLineLosts.Dispose();
            cJoinLineLosts = null;
            if (cJoinReportGroup != null) cJoinReportGroup.Dispose();
            cJoinReportGroup = null;
            if (cMeter != null) cMeter.Dispose();
            cMeter = null;
            if (cCommGroup != null) cCommGroup.Dispose();
            cCommGroup = null;
            if (cUser != null) cUser.Dispose();
                cUser = null;
            if (cPulseMeterCount != null)
                cPulseMeterCount.Dispose();
            cPulseMeterCount = null;
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            Int32 i;
            Boolean Result = false;

            if (cDeviceCE != null)
            {
                DeviceCECaption = cDeviceCE.CECaption;
                DeviceCEChannel = cDeviceCE.CEChannel;
                if (DeviceCECaption != "") Result = true;
                else MessageBox.Show(cConst.DEVICE_CE_CAPTION_ERROR_CAP, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Stop); 
            }
            if (cJoinChannel != null)
            {
                Result = false;
                for (i = 0; i < tmpFreeEnergyTypes.Length; i++)
                {
                    if (cJoinChannel.EnergyType == tmpFreeEnergyTypes[i])
                    {
                        Result = true;
                        break;
                    }
                }
                if (Result)
                {
                    ChannelCollectEnable = cJoinChannel.CollectEnable;
                    ChannelEnergyType = cJoinChannel.EnergyType;
                    ChannelMeterSerial = cJoinChannel.MeterSerial;
                    ChannelMeterID = cJoinChannel.MeterID;
                    ChannelExportNPATSCode = cJoinChannel.ExportNPATSCode;
                    ChannelImportNPATSCode = cJoinChannel.ImportNPATSCode;
                    ChannelValue63002Code = cJoinChannel.Value63002Code;
                    ChannelASKPIdentifier = cJoinChannel.ASKPIdentifier;
                }
                else MessageBox.Show(cConst.JOIN_CHANNEL_ET_ERROR_CAP, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            if (cJoinLineLosts != null)
            {
                CLLLineLength = cJoinLineLosts.LineLength;
                CLLResistance = cJoinLineLosts.Resistance;
                CLLUNominal = cJoinLineLosts.UNominal;
                CLLCableLost = cJoinLineLosts.CableLost;
                CLLAirLost = cJoinLineLosts.AirLost;
                CLLCircuitsAmount = cJoinLineLosts.CircuitsAmount;
                Result = true;
            }
            if (cJoinReportGroup != null)
            {
                tmpReportGroupType = cJoinReportGroup.tmpReportGroupType;
                Result = true;
            }
            if (cMeter != null)
            {
                if (cMeter.Caption != "") Result = true;
                else MessageBox.Show(cConst.METER_CAPTION_ERROR_CAP, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                if (Result)
                {
                    if ((MeterIdx >= 0) && (MeterIdx < cMain.MeterList.Length))
                    {
                        cMain.MeterList[MeterIdx].ItemAction.Changed = true;
                        cMain.MeterList[MeterIdx].Caption = cMeter.Caption;
                        cMain.MeterList[MeterIdx].Precision = cMeter.Precision;
                        cMain.MeterList[MeterIdx].BeforeComma = cMeter.BeforeComma;
                        cMain.MeterList[MeterIdx].AfterComma = cMeter.AfterComma;
                        cMain.MeterList[MeterIdx].MeterConst = cMeter.MeterConst;
                        cMain.MeterList[MeterIdx].Phase = cMeter.Phase;
                        cMain.MeterList[MeterIdx].SelfDemand = cMeter.SelfDemand;
                        Result = true;
                    }
                    else Result = false;
                }                
            }
            if (cCommGroup != null)
            {
                tmpGroupID = cCommGroup.tmpGroupID;
                Result = true;
            }
            if (cUser != null)
            {
                if ((UserIdx >= 0) && (UserIdx < cMain.UserList.Length))
                {
                    if (cUser.UserCaption.Trim() != "") Result = true;
                    else  MessageBox.Show(cConst.USER_CAPTION_ERROR_CAP, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    
                    for (i = 0; (i < cMain.UserList.Length) && (Result); i++)
                    {
                        if ((UserIdx != i) && (cUser.UserCaption == cMain.UserList[i].Caption))
                        {
                            MessageBox.Show(cConst.USER_LIST_CAPTION_ERR_CAP, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            Result = false;
                            break;
                        }
                    }
                    if (Result)
                    {
                        if (cUser.UserChangePassword)
                        {
                            if (cUser.UserNewPassword != cUser.UserConfirmPassword)
                            {
                                MessageBox.Show(cConst.USER_LIST_PASSWORD_ERR_CAP, cConst.ERROR_CAPTION, 
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                                Result = false;
                            }
                        }
                    }
                }
                if (Result)
                {
                    cMain.UserList[UserIdx].ItemAction.Changed = true;
                    cMain.UserList[UserIdx].Caption = cUser.UserCaption;
                    cMain.UserList[UserIdx].AccessID = cUser.UserAccessID;
                    if (cUser.UserChangePassword)
                        cMain.UserList[UserIdx].Password = cMain.MD5Hash(cUser.UserNewPassword);                    
                }               
            }

            if (cNewDeviceType != null)
            {
                Result = true;
                m_NewDevTypeIsUSPD = cNewDeviceType.GetIsUSPD();
                m_NewDevTypeMCCount = cNewDeviceType.GetMCCount();
            }
            if (cPulseMeterCount != null)
            {
                Result = cPulseMeterCount.GetMetersCount(ref m_PulseMetersCount);
                //Result = true;
            }
            if (Result)
            {                
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                Close();
            }
        }
        private void btnClose_Click(object sender, EventArgs e)
        {            
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            Close();
        }
        private void fSetting_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13) btnOk_Click(btnOk, null);
            if (e.KeyChar == 27) btnClose_Click(btnClose, null);
        }
        private void fSetting_FormClosed(object sender, FormClosedEventArgs e)
        {
            ClearWorkArea();
        }

        public Byte GetNewDevTypeIsUSPD()
        {
            return m_NewDevTypeIsUSPD;
        }

        public int GetNewDevTypeMCCount()
        {
            return m_NewDevTypeMCCount;
        }
        //m_PulseMetersCount
        public int GetPulseMetersCount()
        {
            return m_PulseMetersCount;
        }

        
    }
}
